<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医院预约管理系统</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- 配置Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36BFFA',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        gray: {
                            100: '#F2F3F5',
                            200: '#E5E6EB',
                            300: '#C9CDD4',
                            400: '#86909C',
                            500: '#4E5969',
                            600: '#272E3B',
                            700: '#1D2129',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-card {
                box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.06);
            }
            .transition-bg {
                transition: background-color 0.2s ease;
            }
            .transition-transform {
                transition: transform 0.2s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-sans text-gray-700 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <i class="fa fa-hospital-o text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-700">医院预约管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <button class="text-gray-500 hover:text-primary transition-bg">
                <i class="fa fa-bell-o"></i>
            </button>
            <div class="flex items-center space-x-2">
                <span class="hidden md:inline"></span>
            </div>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="flex-grow container mx-auto px-4 py-6">
    <!-- 页面标题和统计卡片 -->


    <!-- 查询和筛选区域 -->
    <div class="bg-white rounded-lg shadow-card p-5 mb-6">
        <form id="searchForm" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <div>
                <label for="patientName" class="block text-sm font-medium text-gray-500 mb-1">患者姓名</label>
                <input type="text" id="patientName" name="patientName"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"
                       placeholder="请输入患者姓名">
            </div>

            <div>
                <label for="status" class="block text-sm font-medium text-gray-500 mb-1">预约状态</label>
                <select id="status" name="status"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <option value="">全部状态</option>
                    <option value="1">待确认</option>
                    <option value="2">已确认</option>
                    <option value="3">已取消</option>
                    <option value="4">已完成</option>
                </select>
            </div>

            <div>
                <label for="appointmentDate" class="block text-sm font-medium text-gray-500 mb-1">预约日期</label>
                <input type="date" id="appointmentDate" name="appointmentDate"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
            </div>

            <div class="flex items-end">
                <button type="submit" class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-bg mr-2 flex items-center">
                    <i class="fa fa-search mr-1"></i> 查询
                </button>
                <button type="button" id="resetBtn" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-300 transition-bg flex items-center">
                    <i class="fa fa-refresh mr-1"></i> 重置
                </button>
            </div>
        </form>
    </div>

    <!-- 预约列表表格 -->
    <div class="bg-white rounded-lg shadow-card overflow-hidden mb-6">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        预约编号
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        患者信息
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        科室/医生
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        预约日期/时间
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        预约类型
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        状态
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        操作
                    </th>
                </tr>
                </thead>
                <tbody id="appointmentTableBody" class="bg-white divide-y divide-gray-200">
                <!-- 表格内容将通过JavaScript动态生成 -->
                <tr class="text-center">
                    <td colspan="7" class="px-6 py-10 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-spinner fa-spin text-primary text-2xl mb-2"></i>
                            <p>加载中...</p>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页控件 -->
        <div id="pagination" class="px-6 py-4 bg-white border-t border-gray-200 flex flex-col sm:flex-row justify-between items-center">
            <div class="text-sm text-gray-500 mb-4 sm:mb-0">
                显示 <span id="startRecord">1</span> 到 <span id="endRecord">10</span> 条，共 <span id="totalRecords">0</span> 条记录
            </div>
            <div class="flex space-x-1">
                <button id="firstPage" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-double-left"></i>
                </button>
                <button id="prevPage" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-left"></i>
                </button>
                <div id="pageNumbers" class="flex space-x-1">
                    <!-- 页码将通过JavaScript动态生成 -->
                </div>
                <button id="nextPage" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-right"></i>
                </button>
                <button id="lastPage" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-double-right"></i>
                </button>
            </div>
        </div>
    </div>
</main>

<!-- 预约详情模态框 -->
<div id="detailModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center sticky top-0 bg-white z-10">
            <h3 class="text-lg font-bold text-gray-700">预约详情</h3>
            <button id="closeDetailModal" class="text-gray-400 hover:text-gray-600">
                <i class="fa fa-times"></i>
            </button>
        </div>

        <div id="appointmentDetail" class="p-6">
            <!-- 详情内容将通过JavaScript动态生成 -->
            <div class="flex justify-center py-10">
                <i class="fa fa-spinner fa-spin text-primary text-3xl"></i>
            </div>
        </div>

        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3 sticky bottom-0 bg-white z-10">
            <button id="closeDetailBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                关闭
            </button>
        </div>
    </div>
</div>

<!-- 更新状态模态框 -->
<div id="statusModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <h3 class="text-lg font-bold text-gray-700">更新预约状态</h3>
            <button id="closeStatusModal" class="text-gray-400 hover:text-gray-600">
                <i class="fa fa-times"></i>
            </button>
        </div>

        <div class="p-6">
            <input type="hidden" id="statusAppointmentId">
            <div class="mb-4">
                <label for="newStatus" class="block text-sm font-medium text-gray-500 mb-1">选择新状态</label>
                <select id="newStatus"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <option value="1">待确认</option>
                    <option value="2">已确认</option>
                    <option value="3">已取消</option>
                    <option value="4">已完成</option>
                </select>
            </div>

            <div>
                <label for="statusRemark" class="block text-sm font-medium text-gray-500 mb-1">备注（可选）</label>
                <textarea id="statusRemark" rows="3"
                          class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"
                          placeholder="请输入备注信息"></textarea>
            </div>
        </div>

        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
            <button id="cancelStatusBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                取消
            </button>
            <button id="confirmStatusBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-bg">
                确认更新
            </button>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="toast" class="fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center">
    <i id="toastIcon" class="mr-2"></i>
    <span id="toastMessage"></span>
</div>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2023 医院预约管理系统 版权所有</p>
    </div>
</footer>

<script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 10;
    let totalPages = 1;
    let totalRecords = 0;

    // DOM 元素加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化页面
        loadAppointments();
        initEventListeners();
        initCharts();
    });

    // 初始化事件监听器
    function initEventListeners() {
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            currentPage = 1; // 重置到第一页
            loadAppointments();
        });

        // 重置按钮
        document.getElementById('resetBtn').addEventListener('click', function() {
            document.getElementById('searchForm').reset();
            currentPage = 1; // 重置到第一页
            loadAppointments();
        });

        // 分页按钮事件
        document.getElementById('firstPage').addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage = 1;
                loadAppointments();
            }
        });

        document.getElementById('prevPage').addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage--;
                loadAppointments();
            }
        });

        document.getElementById('nextPage').addEventListener('click', function() {
            if (currentPage < totalPages) {
                currentPage++;
                loadAppointments();
            }
        });

        document.getElementById('lastPage').addEventListener('click', function() {
            if (currentPage < totalPages) {
                currentPage = totalPages;
                loadAppointments();
            }
        });

        // 详情模态框关闭按钮
        document.getElementById('closeDetailModal').addEventListener('click', closeDetailModal);
        document.getElementById('closeDetailBtn').addEventListener('click', closeDetailModal);

        // 状态更新模态框关闭按钮
        document.getElementById('closeStatusModal').addEventListener('click', closeStatusModal);
        document.getElementById('cancelStatusBtn').addEventListener('click', closeStatusModal);

        // 确认更新状态
        document.getElementById('confirmStatusBtn').addEventListener('click', updateAppointmentStatus);
    }

    // 初始化统计图表
    function initCharts() {
        // 这里可以添加预约统计图表
        // 示例：创建一个简单的预约类型分布图表
        const ctx = document.createElement('canvas');
        // 实际项目中可以将图表添加到页面适当位置
    }

    // 加载预约列表（分页查询功能）
    function loadAppointments() {
        // 显示加载状态
        const tableBody = document.getElementById('appointmentTableBody');
        tableBody.innerHTML = `
        <tr class="text-center">
          <td colspan="7" class="px-6 py-10 text-gray-500">
            <div class="flex flex-col items-center">
              <i class="fa fa-spinner fa-spin text-primary text-2xl mb-2"></i>
              <p>加载中...</p>
            </div>
          </td>
        </tr>
      `;

        // 获取查询参数
        const patientName = document.getElementById('patientName').value;
        const status = document.getElementById('status').value;
        const appointmentDate = document.getElementById('appointmentDate').value;

        // 模拟API请求 - 实际项目中替换为真实的API调用
        setTimeout(() => {
            // 模拟数据
            const mockData = generateMockAppointments(currentPage, pageSize, patientName, status);
            totalRecords = mockData.total;
            totalPages = Math.ceil(totalRecords / pageSize);

            // 更新表格内容
            renderAppointmentTable(mockData.records);

            // 更新分页控件
            updatePagination();

            // 更新统计数据
            updateStatistics();

        }, 800); // 模拟网络延迟
    }

    // 渲染预约表格
    function renderAppointmentTable(appointments) {
        const tableBody = document.getElementById('appointmentTableBody');

        if (appointments.length === 0) {
            tableBody.innerHTML = `
          <tr class="text-center">
            <td colspan="7" class="px-6 py-10 text-gray-500">
              <div class="flex flex-col items-center">
                <i class="fa fa-search text-gray-300 text-2xl mb-2"></i>
                <p>没有找到匹配的预约记录</p>
              </div>
            </td>
          </tr>
        `;
            return;
        }

        let html = '';
        appointments.forEach(appointment => {
            // 格式化状态显示
            let statusClass = '';
            let statusText = '';

            switch(appointment.status) {
                case 1:
                    statusClass = 'bg-yellow-100 text-yellow-800';
                    statusText = '待确认';
                    break;
                case 2:
                    statusClass = 'bg-green-100 text-green-800';
                    statusText = '已确认';
                    break;
                case 3:
                    statusClass = 'bg-red-100 text-red-800';
                    statusText = '已取消';
                    break;
                case 4:
                    statusClass = 'bg-blue-100 text-blue-800';
                    statusText = '已完成';
                    break;
            }

            // 格式化预约类型
            let typeText = '';
            switch(appointment.appointmentType) {
                case 1:
                    typeText = '普通';
                    break;
                case 2:
                    typeText = '专家';
                    break;
                case 3:
                    typeText = '急诊';
                    break;
            }

            html += `
          <tr class="hover:bg-gray-50 transition-bg">
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm font-medium text-gray-900">${appointment.appointmentNo}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm text-gray-900">${appointment.patientName}</div>
              <div class="text-xs text-gray-500">${appointment.patientPhone}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm text-gray-900">${appointment.departmentName}</div>
              <div class="text-xs text-gray-500">${appointment.doctorName || '未分配'}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              ${appointment.appointmentDate}<br>
              ${appointment.timeSlot}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              ${typeText}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                ${statusText}
              </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
              <button onclick="viewAppointmentDetail(${appointment.id})"
                      class="text-primary hover:text-primary/80 mr-3">
                <i class="fa fa-eye mr-1"></i>查看
              </button>
              <button onclick="showUpdateStatusModal(${appointment.id}, ${appointment.status})"
                      class="text-warning hover:text-warning/80">
                <i class="fa fa-edit mr-1"></i>状态
              </button>
            </td>
          </tr>
        `;
        });

        tableBody.innerHTML = html;
    }

    // 更新分页控件
    function updatePagination() {
        // 更新记录信息
        document.getElementById('totalRecords').textContent = totalRecords;
        document.getElementById('startRecord').textContent = totalRecords > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        document.getElementById('endRecord').textContent = Math.min(currentPage * pageSize, totalRecords);

        // 更新页码按钮
        const pageNumbersContainer = document.getElementById('pageNumbers');
        pageNumbersContainer.innerHTML = '';

        // 生成页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);

        // 调整显示的页码范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md ${i === currentPage ? 'bg-primary text-white border-primary' : 'bg-white text-gray-500 border-gray-300 hover:bg-gray-50'}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', function() {
                currentPage = i;
                loadAppointments();
            });
            pageNumbersContainer.appendChild(pageBtn);
        }

        // 更新分页按钮状态
        document.getElementById('firstPage').disabled = currentPage === 1;
        document.getElementById('prevPage').disabled = currentPage === 1;
        document.getElementById('nextPage').disabled = currentPage === totalPages;
        document.getElementById('lastPage').disabled = currentPage === totalPages;
    }

    // 查看预约详情（查询单个预约功能）
    function viewAppointmentDetail(id) {
        // 显示模态框和加载状态
        const detailModal = document.getElementById('detailModal');
        const appointmentDetail = document.getElementById('appointmentDetail');

        detailModal.classList.remove('hidden');
        detailModal.classList.add('flex');
        appointmentDetail.innerHTML = `
        <div class="flex justify-center py-10">
          <i class="fa fa-spinner fa-spin text-primary text-3xl"></i>
        </div>
      `;

        // 模拟API请求 - 实际项目中替换为真实的API调用
        setTimeout(() => {
            // 模拟获取单个预约详情
            const appointment = getMockAppointmentDetail(id);

            // 格式化状态显示
            let statusClass = '';
            let statusText = '';

            switch(appointment.status) {
                case 1:
                    statusClass = 'bg-yellow-100 text-yellow-800';
                    statusText = '待确认';
                    break;
                case 2:
                    statusClass = 'bg-green-100 text-green-800';
                    statusText = '已确认';
                    break;
                case 3:
                    statusClass = 'bg-red-100 text-red-800';
                    statusText = '已取消';
                    break;
                case 4:
                    statusClass = 'bg-blue-100 text-blue-800';
                    statusText = '已完成';
                    break;
            }

            // 格式化预约类型
            let typeText = '';
            switch(appointment.appointmentType) {
                case 1:
                    typeText = '普通';
                    break;
                case 2:
                    typeText = '专家';
                    break;
                case 3:
                    typeText = '急诊';
                    break;
            }

            // 格式化来源
            let sourceText = '';
            switch(appointment.source) {
                case 1:
                    sourceText = '微信';
                    break;
                case 2:
                    sourceText = 'APP';
                    break;
                case 3:
                    sourceText = '网站';
                    break;
                case 4:
                    sourceText = '电话';
                    break;
            }

            // 格式化支付状态
            const payStatusText = appointment.isPaid ? '<span class="text-success">已支付</span>' : '<span class="text-danger">未支付</span>';

            // 渲染详情内容
            appointmentDetail.innerHTML = `
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h4 class="text-sm font-medium text-gray-500 mb-1">预约编号</h4>
              <p class="text-gray-900 mb-4">${appointment.appointmentNo}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">患者姓名</h4>
              <p class="text-gray-900 mb-4">${appointment.patientName}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">联系电话</h4>
              <p class="text-gray-900 mb-4">${appointment.patientPhone}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">身份证号</h4>
              <p class="text-gray-900 mb-4">${appointment.patientIdCard || '未提供'}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">科室</h4>
              <p class="text-gray-900 mb-4">${appointment.departmentName}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">医生</h4>
              <p class="text-gray-900 mb-4">${appointment.doctorName || '未分配'}</p>
            </div>

            <div>
              <h4 class="text-sm font-medium text-gray-500 mb-1">预约日期</h4>
              <p class="text-gray-900 mb-4">${appointment.appointmentDate}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">时间段</h4>
              <p class="text-gray-900 mb-4">${appointment.timeSlot}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">预约类型</h4>
              <p class="text-gray-900 mb-4">${typeText}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">预约来源</h4>
              <p class="text-gray-900 mb-4">${sourceText}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">预约费用</h4>
              <p class="text-gray-900 mb-4">¥${appointment.fee.toFixed(2)}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">支付状态</h4>
              <p class="mb-4">${payStatusText}</p>

              <h4 class="text-sm font-medium text-gray-500 mb-1">当前状态</h4>
              <p class="mb-4">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                  ${statusText}
                </span>
              </p>
            </div>
          </div>

          <div class="mt-6">
            <h4 class="text-sm font-medium text-gray-500 mb-1">症状描述</h4>
            <p class="text-gray-900 mb-4 p-3 bg-gray-50 rounded-md min-h-[80px]">${appointment.symptoms || '无'}</p>
          </div>

          <div class="mt-6">
            <h4 class="text-sm font-medium text-gray-500 mb-1">备注</h4>
            <p class="text-gray-900 mb-4 p-3 bg-gray-50 rounded-md min-h-[60px]">${appointment.remark || '无'}</p>
          </div>

          <div class="mt-6 pt-4 border-t border-gray-200 text-sm text-gray-500 flex justify-between">
            <div>创建时间: ${appointment.createTime}</div>
            <div>更新时间: ${appointment.updateTime}</div>
          </div>
        `;

        }, 600); // 模拟网络延迟
    }

    // 关闭详情模态框
    function closeDetailModal() {
        const detailModal = document.getElementById('detailModal');
        detailModal.classList.remove('flex');
        detailModal.classList.add('hidden');
    }

    // 显示更新状态模态框
    function showUpdateStatusModal(id, currentStatus) {
        // 设置当前预约ID
        document.getElementById('statusAppointmentId').value = id;

        // 设置当前状态为选中
        document.getElementById('newStatus').value = currentStatus;

        // 清空备注
        document.getElementById('statusRemark').value = '';

        // 显示模态框
        const statusModal = document.getElementById('statusModal');
        statusModal.classList.remove('hidden');
        statusModal.classList.add('flex');
    }

    // 关闭状态更新模态框
    function closeStatusModal() {
        const statusModal = document.getElementById('statusModal');
        statusModal.classList.remove('flex');
        statusModal.classList.add('hidden');
    }

    // 更新预约状态（更新预约状态功能）
    function updateAppointmentStatus() {
        const id = document.getElementById('statusAppointmentId').value;
        const newStatus = document.getElementById('newStatus').value;
        const remark = document.getElementById('statusRemark').value;

        // 显示加载状态
        document.getElementById('confirmStatusBtn').disabled = true;
        document.getElementById('confirmStatusBtn').innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 处理中...';

        // 模拟API请求 - 实际项目中替换为真实的API调用
        setTimeout(() => {
            // 模拟更新成功
            closeStatusModal();
            showToast('success', '预约状态更新成功');

            // 重新加载列表
            loadAppointments();

            // 恢复按钮状态
            document.getElementById('confirmStatusBtn').disabled = false;
            document.getElementById('confirmStatusBtn').textContent = '确认更新';

        }, 800); // 模拟网络延迟
    }

    // 显示提示消息
    function showToast(type, message) {
        const toast = document.getElementById('toast');
        const toastIcon = document.getElementById('toastIcon');
        const toastMessage = document.getElementById('toastMessage');

        // 设置提示类型和消息
        toastMessage.textContent = message;

        if (type === 'success') {
            toast.className = 'fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center bg-success text-white';
            toastIcon.className = 'fa fa-check-circle mr-2';
        } else if (type === 'error') {
            toast.className = 'fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center bg-danger text-white';
            toastIcon.className = 'fa fa-times-circle mr-2';
        } else if (type === 'warning') {
            toast.className = 'fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center bg-warning text-white';
            toastIcon.className = 'fa fa-exclamation-triangle mr-2';
        }

        // 显示提示
        setTimeout(() => {
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 3秒后隐藏提示
        setTimeout(() => {
            toast.style.transform = 'translateX(calc(100% + 20px))';
        }, 3000);
    }

    // 更新统计数据
    function updateStatistics() {
        // 这里只是模拟数据，实际项目中应该从API获取
        document.getElementById('todayAppointments').textContent = Math.floor(Math.random() * 10) + 15;
        document.getElementById('pendingAppointments').textContent = Math.floor(Math.random() * 5) + 3;
        document.getElementById('confirmedAppointments').textContent = Math.floor(Math.random() * 20) + 30;
        document.getElementById('cancelledAppointments').textContent = Math.floor(Math.random() * 5) + 1;
    }

    // 生成模拟预约数据（用于演示）
    function generateMockAppointments(page, pageSize, patientNameFilter, statusFilter) {
        const total = 87; // 总记录数
        const records = [];

        // 科室列表
        const departments = ['内科', '外科', '儿科', '妇产科', '眼科', '口腔科', '皮肤科', '骨科'];

        // 医生列表
        const doctors = ['张医生', '李医生', '王医生', '赵医生', '刘医生', '陈医生', '杨医生', '黄医生'];

        // 时间段
        const timeSlots = ['上午 8:00-9:00', '上午 9:00-10:00', '上午 10:00-11:00', '下午 14:00-15:00', '下午 15:00-16:00', '下午 16:00-17:00'];

        // 生成当前页数据
        const start = (page - 1) * pageSize + 1;
        const end = Math.min(page * pageSize, total);

        for (let i = start; i <= end; i++) {
            // 随机生成数据
            const status = Math.floor(Math.random() * 4) + 1;
            const appointmentType = Math.floor(Math.random() * 3) + 1;
            const source = Math.floor(Math.random() * 4) + 1;
            const departmentIndex = Math.floor(Math.random() * departments.length);
            const doctorIndex = Math.floor(Math.random() * doctors.length);
            const timeSlotIndex = Math.floor(Math.random() * timeSlots.length);

            // 随机日期（近30天内）
            const date = new Date();
            date.setDate(date.getDate() - Math.floor(Math.random() * 30));
            const formattedDate = date.toISOString().split('T')[0];

            // 生成患者姓名
            const patientNames = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十', '郑一', '王二'];
            const patientIndex = Math.floor(Math.random() * patientNames.length);
            const patientName = patientNames[patientIndex];

            // 应用筛选条件
            if (patientNameFilter && !patientName.includes(patientNameFilter)) {
                continue;
            }

            if (statusFilter && status != statusFilter) {
                continue;
            }

            // 生成模拟预约记录
            const appointment = {
                id: i,
                appointmentNo: `AP${new Date().getFullYear()}${(i + 1000).toString().slice(1)}`,
                patientId: 10000 + i,
                patientName: patientName,
                patientPhone: `13${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 100000000)}`,
                patientIdCard: `31010${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 100000000000)}`,
                departmentId: departmentIndex + 1,
                departmentName: departments[departmentIndex],
                doctorId: doctorIndex + 100,
                doctorName: doctors[doctorIndex],
                appointmentDate: formattedDate,
                timeSlot: timeSlots[timeSlotIndex],
                symptoms: i % 5 === 0 ? null : `患者主诉${i % 3 === 0 ? '头痛' : i % 3 === 1 ? '发热' : '咳嗽'}，持续${i % 5 + 1}天，无其他明显症状。`,
                appointmentType: appointmentType,
                status: status,
                source: source,
                fee: appointmentType === 1 ? 50 : appointmentType === 2 ? 100 : 80,
                isPaid: Math.random() > 0.2,
                createTime: new Date(date.getTime() - Math.floor(Math.random() * 86400000 * 2)).toLocaleString(),
                updateTime: new Date(date.getTime() + Math.floor(Math.random() * 86400000)).toLocaleString(),
                createBy: '系统',
                updateBy: '系统',
                remark: i % 4 === 0 ? null : `预约${status === 3 ? '已取消，原因：患者主动取消' : '正常'}`
            };

            records.push(appointment);
        }

        return {
            total: total,
            records: records
        };
    }

    // 获取单个预约详情（用于演示）
    function getMockAppointmentDetail(id) {
        // 从模拟数据中查找指定ID的预约
        const mockData = generateMockAppointments(1, 100);
        return mockData.records.find(item => item.id == id) || mockData.records[0];
    }
</script>
</body>
</html>
